<template>
  <div class="comment-form">
    <h3>发表评论</h3>
    <el-form :model="form" @submit.prevent="handleSubmit">
      <el-form-item label="评分">
        <el-rate v-model="form.rating" :max="5" />
      </el-form-item>
      <el-form-item label="评论内容">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="3"
          placeholder="请输入您的评论"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          发表评论
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { commentApi, type CommentParams } from '@/api/user/comment'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

const props = defineProps<{
  targetId: number
  targetType: 'SERVICE' | 'DESTINATION' | 'POST'
}>()

const emit = defineEmits<{
  (e: 'success'): void
}>()

const userStore = useUserStore()
const submitting = ref(false)
const form = ref<CommentParams>({
  content: '',
  rating: 5
})

const handleSubmit = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }

  if (!form.value.content.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  submitting.value = true
  try {
    let response
    switch (props.targetType) {
      case 'SERVICE':
        response = await commentApi.addServiceComment(props.targetId, form.value)
        break
      case 'DESTINATION':
        response = await commentApi.addDestinationComment(props.targetId, form.value)
        break
      case 'POST':
        response = await commentApi.addPostComment(props.targetId, form.value)
        break
    }

    if (response?.data.code === 200) {
      ElMessage.success('评论成功')
      form.value.content = ''
      form.value.rating = 5
      emit('success')
    }
  } catch (error) {
    console.error('评论失败:', error)
    ElMessage.error('评论失败')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.comment-form {
  margin-top: 2rem;
  padding: 1rem;
  background: #f9f9f9;
  border-radius: 8px;
}

h3 {
  margin-bottom: 1rem;
}
</style> 